<?php
/**
 * Created by PhpStorm.
 * User: Lee
 * Date: 2020/1/3
 * Time: 9:51
 */
namespace App\Services\Backend\System;

use App\Common\Exception\ErrorException;
use App\Models\Backend\System\Operation;
use Illuminate\Support\Facades\DB;

/**
 * 系统管理-角色管理 (服务)
 */
class RoleService
{
    /** @var \App\Repositories\Backend\System\RoleRepository $roleRepository */
    private $roleRepository;

    public function __construct()
    {
        $this->roleRepository = app('roleRepository');
    }

    // 获取列表
    public function getList($requestData){
        $filters = [];
        // 搜索
        if(isset($requestData['filters']['rolename']) && !empty($requestData['filters']['rolename'])){
            $filters[] = ['rolename', 'like', '%'.$requestData['filters']['rolename'].'%'];
        }
        if(isset($requestData['limit']) && !empty($requestData['limit'])){
            $limit = $requestData['limit'];
        }else{
            $limit = 10;
        }

        $filters[] = ['id', '!=', SYSTEMADMIN_ROLEID];

        $sorts = ['id' => 'asc'];
        $result = $this->roleRepository->getList($filters,$sorts,$requestData['page'],['*'],$limit);
        $arr = $result->toArray();
        foreach ($arr['data'] as $k=>$item) {
            $user_total = DB::table('role_user')->where('role_id','=',$item['id'])->count('user_id');
            $op_total = DB::table('rolepowers')->where('role_id','=',$item['id'])->count('actionid');
            $arr['data'][$k]['user_total'] = $user_total;
            $arr['data'][$k]['op_total'] = $op_total;
        }

        return $arr;
    }

    // 获取所有角色
    public function getAll($filters=[],$sort=[],$columns = ['*']){
        if (empty($filters)){
            $filters=[['id','!=',8]];
        }
        return $this->roleRepository->getAll($filters,$sort,$columns);
    }

    public function get($id, $keyName = 'id',$columns = ['*']){
        $row = $this->roleRepository->get($id, $keyName, $columns);
        if ($row && $row->status == '2'){
            throw new ErrorException('该角色被禁用');
        }
        return $row;
    }

    // 新增
    public function add($requestData){
        $id = $this->roleRepository->add($requestData);
        return $id;
    }
    //设置开启/禁用
    public function setRoleStatus($requestData){
        $row = $this->roleRepository->get($requestData['id']);
        if (!$row){
            throw new ErrorException('角色不存在');
        }
        $this->roleRepository->edit([
            'status' => $requestData['status']
        ],$requestData['id']);
    }

    //编辑
    public function edit($requestData){
        $id = $requestData['id'];
        $role = $this->roleRepository->get($id);
        if(!$role){
            throw new ErrorException('角色不存在');
        }

        $this->roleRepository->edit($requestData, $id);
    }

    //删除
    public function delete($requestData){
        $id = $requestData['id'];
        $role = $this->roleRepository->get($id);
        if(!$role){
            throw new ErrorException('角色不存在');
        }
        $this->roleRepository->delete($id);
    }

     /**
     * 获取所有角色的权限
     * @return array
     * @throws ErrorException
     */
    public function getAllRolesPowers()
    {
        $filters = [];
        $filters[] = ['id','!=',SYSTEMADMIN_ROLEID];
        $filters[] = ['status','=','1'];

        //控制系统管理员权限显示
        // $adminFlag = auth()->user()->admin_flag;
        // $roleId = $adminFlag == 2 ? 5 : 4;
        // $filters[] = ['id','<',$roleId];

        $roles = $this->roleRepository->getAll($filters);
        $returnData = [
            'role_data' => [],
            'admin_data' => [],
        ];
        foreach ($roles as $role) {
            $returnData['role_data'][] = [
                'roleid' => $role->id,
                'rolename' => $role->rolename,
                'rolepowers' => $this->getRolePowers(['id'=>$role->id])
            ];
        }
        $returnData['admin_data'] = $this->getPowerTree(['role_id'=>SYSTEMADMIN_ROLEID]);

        return $returnData;
    }

    public function getPowerTree($requestData){
        /** @var \App\Services\Backend\System\OperationService $operationService */
        $operationService = app('operationService');

        $menus = [];
        $affairObject = [];
        $eventObject = [];
        $operationObject = [];
        $operations = $operationService->getVisibleAffairEventOperation($requestData['role_id']);
        foreach ($operations as $item){
            $item =  get_object_vars($item);
            if (isset($affairObject['id']) && $affairObject['id'] == $item['affairtypeid']){    // 如果设置过事物
                if (isset($eventObject['id']) && $eventObject['id'] == $item['eventtypeid']){
                    if(isset($operationObject['id']) && $operationObject['id'] != $item['actionid']){
                        $operationObject = [
                            'id' => $item['actionid'],
                            'title' => $item['actionname'],
                        ];
                        $menus[$item['affairtypeid']]['children'][$item['eventtypeid']]['children'][$item['actionid']] = $operationObject;
                    }
                }else{
                    if(isset($eventObject['id']) && $eventObject['id'] != $item['eventtypeid']){
                        $eventObject = [
                            'id' => $item['eventtypeid'],
                            'title' => $item['eventtypename'],
                            'spread' => true,
                            'children' => array(),
                        ];
                        $menus[$item['affairtypeid']]['children'][$item['eventtypeid']] = $eventObject;
                        //  事件中push操作
                        $operationObject = [
                            'id' => $item['actionid'],
                            'title' => $item['actionname'],
                        ];
                        $menus[$item['affairtypeid']]['children'][$item['eventtypeid']]['children'][$item['actionid']] = $operationObject;
                    }
                }
            }else{
                $affairObject = [
                    'id' => $item['affairtypeid'],
                    'title' => $item['affairtypename'],
                    'spread' => true,
                    'children' => array(),
                ];
                $menus[$item['affairtypeid']] = $affairObject;

                $eventObject = [
                    'id' => $item['eventtypeid'],
                    'title' => $item['eventtypename'],
                    'spread' => true,
                    'children' => array(),
                ];
                $menus[$item['affairtypeid']]['children'][$item['eventtypeid']] = $eventObject;

                //  事件中push操作
                $operationObject = [
                    'id' => $item['actionid'],
                    'title' => $item['actionname'],
                ];
                $menus[$item['affairtypeid']]['children'][$item['eventtypeid']]['children'][$item['actionid']] = $operationObject;
            }
        }

        $menus = array_values($menus);
        foreach($menus as $k => $v){
            $menus[$k]['children'] = array_values($menus[$k]['children']);

            foreach($menus[$k]['children'] as $k_g => $v_g){
                $menus[$k]['children'][$k_g]['children'] =  array_values( $menus[$k]['children'][$k_g]['children']);
            }
        }

        return $menus;
    }

    //获取角色权限
    public function getRolePowers($requestData){
        $id = $requestData['id'];
        $role = $this->roleRepository->get($id);
        if(!$role){
            throw new ErrorException('角色不存在');
        }
        $powers = $role->powers()->get();
        $powers = $powers->toArray();
        $powers = array_column($powers, 'actionid');
        return $powers;
    }

    //设置角色权限
    public function setRolePowers($requestData){
        // $id = $requestData['id'];
        // $role = $this->roleRepository->get($id);
        // if(!$role){
        //     throw new ErrorException('角色不存在');
        // }
        // $actionids = $requestData['actionids'];
        // $role->powers()->detach();
        // $role->powers()->attach($actionids);
        $actionids = $requestData['actionids'];
        if (is_array($actionids)){
            foreach ($actionids as $actionid) {
                $role_id = explode('_',$actionid['name'])[0];
                $operation_id = explode('_',$actionid['name'])[1];

                $is_checked = $actionid['is_checked'];
                if ($is_checked == 1){
                    DB::table('rolepowers')->insert([
                        'role_id' => $role_id,
                        'actionid'=>$operation_id
                    ]);
                } else {
                    DB::table('rolepowers')->where('role_id', $role_id)->where('actionid', $operation_id)->delete();
                }
            }
        }
    }
    /**
     * @Description: 初始化管理员权限
     * @Author: kzj
     * @datetime: 2022-02-11
     */
    public function initAdminPower()
    {
        $user = auth()->user();
        $role = $user->roles()->get()->pluck('id')->unique()->max();

        if($role != SYSTEMADMIN_ROLEID) {
            throw new ErrorException('非系统管理员无法操作');
        }

        $op = Operation::all()->pluck('actionid')->toArray();

        DB::beginTransaction();
        try {
            $adminPowers = [];
            foreach($op as $o) {
                $adminPowers[] = [
                    'role_id' => SYSTEMADMIN_ROLEID,
                    'actionid' => $o
                ];
            }

            if(!empty($adminPowers)) {
                DB::table('rolepowers')->where('role_id', SYSTEMADMIN_ROLEID)->delete();
                DB::table('rolepowers')->insert($adminPowers);
            }

            DB::commit();
        } catch (Exception $exception) {
            DB::rollback();
            throw new ErrorException('数据提交错误！');
        }

        return true;
    }

    //*******************外部调用方法****************************************************
    public function getCore($id, $keyName = 'id',$columns = ['*']){
        return $this->roleRepository->get($id,$keyName,$columns);
    }

}
